﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Imports System.IO

Partial Class Control_QuanLyHoSoThongBaoThuHoi_List
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            Loaddrop()
            BindToGrid()
        End If
    End Sub
    Protected Sub Loaddrop()
        Using _data As New VSEntities
            Dim p = (From q In _data.Status Where q.FunctionId = Function_Name.CertifiedHousehold Order By q.StatusId Select q).ToList
            With ddlTrangThai
                .DataSource = p
                .DataValueField = "StatusId"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("---Tất cả---", -1))
            End With

        End Using
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1 _
            , Optional ByVal strBiz_VietName As String = "" _
            , Optional ByVal strBiz_HeadOffice As String = "" _
            , Optional ByVal strOw_CardID As String = "" _
            , Optional ByVal intProvinceId As Integer = -1 _
            , Optional ByVal intTrangThaiId As Integer = -1 _
            )

        intProvinceId = Session("HuyenId")
        'intStatusId = TinhTrangHoSo.ChoDuyet
        Using data As New VSEntities
            Dim arrSearch() As String = {iPage, strBiz_VietName, strBiz_HeadOffice, strOw_CardID, _
                                         intProvinceId, intTrangThaiId}
            ViewState("search") = arrSearch
            'So ban ghi muon the hien tren trang

            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            'intStatusId = ddlStatusId.SelectedValue

            Dim p As List(Of uspCertifiedHouseholdThongBao_Result) = (From a In data.uspCertifiedHouseholdThongBao(strBiz_VietName _
                    , strBiz_HeadOffice _
                    , strOw_CardID _
                    , intProvinceId _
                    , intTrangThaiId _
                    , iPage _
                    , intPag_Size)).ToList

            Dim strKey_Name() As String = {"CertifiedID", "CertifiedCode", "Biz_VietName", "StatusId"}
            'Tong so ban ghi
            If p.Count > 0 Then
                hidCount.Value = p.FirstOrDefault.Total()
                Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
            End If

            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            If (hidCount.Value > 0) Then
                lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
            Else
                lblTotal.Text = ""
            End If
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(CInt(lnkTile.ToolTip) _
       , arrSearch(1) _
       , arrSearch(2) _
       , arrSearch(3) _
       , arrSearch(4) _
       , arrSearch(5) _
            )
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region
#Region "Event for control"
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1

            Dim hplCertifiedCode As HyperLink = CType(e.Row.FindControl("hplCertifiedCode"), HyperLink)
            hplCertifiedCode.NavigateUrl = "../../Page/QuanLyHoSoThongBaoThuHoi/Detail.aspx?Certifiedid=" & grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString
            hplCertifiedCode.Text = grdShow.DataKeys(e.Row.RowIndex)("CertifiedCode")
            Dim hplBiz_VietName As HyperLink = CType(e.Row.FindControl("hplBiz_VietName"), HyperLink)
            hplBiz_VietName.NavigateUrl = "../../Page/QuanLyHoSoThongBaoThuHoi/Detail.aspx?Certifiedid=" & grdShow.DataKeys(e.Row.RowIndex)("CertifiedID").ToString
            hplBiz_VietName.Text = grdShow.DataKeys(e.Row.RowIndex)("Biz_VietName")

            Using data As New VSEntities
                Dim lblStatusId As Label = CType(e.Row.FindControl("lblStatusId"), Label)
                Dim _l As Integer = grdShow.DataKeys(e.Row.RowIndex)("StatusId")
                lblStatusId.Text = (From h In data.Status Where h.StatusId = _l Select h.Title).FirstOrDefault
                lblStatusId.CssClass = "hoso_" & _l.ToString
            End Using


        End If
    End Sub
#End Region
#Region "Search"
    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        BindToGrid(1 _
            , txtBiz_vietname.Text.Trim _
            , txtBiz_HeadOffice.Text.Trim _
            , txtOw_cardid.Text.Trim _
            , Session("HuyenId") _
            , ddlTrangThai.SelectedValue _
            )

    End Sub
    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1) _
       , arrSearch(2) _
       , arrSearch(3) _
       , arrSearch(4) _
       , arrSearch(5) _
         )
    End Sub
    Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click
        txtBiz_vietname.Text = ""
        txtOw_cardid.Text = ""
        txtBiz_HeadOffice.Text = ""
        drpPage_Size.SelectedIndex = -1
        ddlTrangThai.SelectedIndex = -1
        BindToGrid(1)
    End Sub
#End Region

    Protected Sub btnExportExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportExcel.Click
        Try
            Dim _fieldName As String() = {"RowNum", "Biz_VietName", "Biz_HeadOffice", "Ow_Name", "Ow_Resident", "Ow_CardID", "Ow_CardDate", "CertifiedCode" _
                                         , "CertifiedDate", "Biz_InvestCapital", "NganhNgheKinhDoanh", "Biz_Tel", "TinhTrang", "Ow_TaxCode"}
            Using data As New VSEntities
                Dim _fileName As String = "ThongBao_" & Date.Now.ToFileTimeUtc()

                Dim intProvinceId = Session("HuyenId")
                Dim p As List(Of uspCertifiedHouseholdThongBao_Result) = (From a In data.uspCertifiedHouseholdThongBao(txtBiz_vietname.Text _
                        , txtBiz_HeadOffice.Text _
                        , txtOw_cardid.Text _
                        , intProvinceId _
                        , ddlTrangThai.SelectedValue _
                        , 1 _
                        , 1000000)).ToList

                Dim applicationPath As String = Server.MapPath(Request.ApplicationPath)
                If Not applicationPath.EndsWith("\") Then
                    applicationPath = applicationPath + "\"
                End If
                Dim licenseFile As String = Path.Combine(applicationPath, "bin\Aspose.Cells.lic")
                Dim license As Aspose.Cells.License = New Aspose.Cells.License()
                license.SetLicense(licenseFile)
                Dim _workbook As New Aspose.Cells.Workbook(Server.MapPath("~/Template/Thue.xls"))
                Dim _workSheet As Aspose.Cells.Worksheet = _workbook.Worksheets(0)
                _workSheet.Cells.ImportCustomObjects(CType(p, System.Collections.ICollection), _fieldName, False, 1, 0, p.Count, True, "dd/MM/yyyy", False)
                _workSheet.AutoFitColumns()
                Cls_Common.CreateDir(Server.MapPath("~/Template/ReportDownload/"))
                _workbook.Save(Server.MapPath("~/Template/ReportDownload/" & _fileName & ".xls"))
                Excute_Javascript("Alertbox('Xuất dữ liệu thành công'); SetDownFile('" & ResolveUrl("~/Template/ReportDownload/" & _fileName & ".xls") & "')", Me.Page, True)
            End Using
        Catch ex As Exception
            log4net.Config.XmlConfigurator.Configure()
            log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
            Excute_Javascript("Alertbox('Xuất dữ liệu thất bại." & ex.Message & "');", Me.Page, True)
        End Try


    End Sub

End Class
